<template>
  <van-button
    :loading="loading"
    plain
    :icon="is_collected ? 'star' : 'star-o'"
    :color="is_collected ? '#3296fa' : '#777'"
    @click="onCollect"
  />
</template>
<script>
import { addCollect, deleteCollect } from "@/api/article";
export default {
  model: {
    prop: "is_collected",
    event: "update-collect"
  },
  props: {
    is_collected: {
      type: Boolean,
      required: true
    },
    artId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      loading: false
    };
  },
  methods: {
    async onCollect() {
      // 判断当前是否登录
      if (!this.$store.state.user) {
        this.$toast("请先登录");
        return this.$router.push("/login?redirect=" + this.$route.path);
      }
      this.loading = true;
      try {
        if (this.is_collected) {
          // 当前是收藏状态，要取消收藏
          await deleteCollect(this.artId);
        } else {
          await addCollect(this.artId);
        }
        this.$emit("update-collect", !this.is_collected);
        this.$toast.success(this.is_collected ? "取消收藏成功" : "收藏成功");
      } catch (error) {
        this.$toast.fail(this.is_collected ? "取消收藏失败" : "收藏失败");
      }
      this.loading = false;
    }
  }
};
</script>
<style lang="less" scoped>
.van-button--plain {
  border: none;
}
</style>
